<template>
  <van-swipe-cell>
    <van-cell @click="onTodoClick">
      <template #title>
        <div class="todo-item">
          <van-checkbox
            :model-value="todo.completed"
            @click.stop="onToggleComplete"
            :checked-color="priorityColor"
          >
            <div class="todo-content">
              <span :class="{ 'completed': todo.completed }" class="todo-title">{{ todo.title }}</span>
              <div v-if="todo.description" class="todo-description">
                {{ truncatedDescription }}
              </div>
              <div class="todo-meta">
                <van-tag :type="priorityTagType" size="small">{{ priorityText }}</van-tag>
                <van-tag v-if="todo.due_date" :type="dueDateTagType" size="small">{{ formattedDueDate }}</van-tag>
              </div>
            </div>
          </van-checkbox>
        </div>
      </template>
    </van-cell>
    <template #right>
      <van-button square type="primary" text="Edit" @click.stop="onEdit" />
      <van-button square type="danger" text="Delete" @click.stop="onDelete" />
    </template>
  </van-swipe-cell>
</template>

<script setup>
import { computed } from 'vue';
import { showDialog, showToast } from 'vant';
import { todoApi } from '../api';

const props = defineProps({
  todo: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['todo-updated', 'edit-todo']);

// Computed properties
const truncatedDescription = computed(() => {
  if (!props.todo.description) return '';
  return props.todo.description.length > 50
    ? props.todo.description.substring(0, 50) + '...'
    : props.todo.description;
});

const priorityText = computed(() => {
  switch (props.todo.priority) {
    case 1: return 'High';
    case 2: return 'Medium';
    case 3: return 'Low';
    default: return 'Medium';
  }
});

const priorityTagType = computed(() => {
  switch (props.todo.priority) {
    case 1: return 'danger';
    case 2: return 'warning';
    case 3: return 'success';
    default: return 'warning';
  }
});

const priorityColor = computed(() => {
  switch (props.todo.priority) {
    case 1: return '#ee0a24';
    case 2: return '#ff976a';
    case 3: return '#07c160';
    default: return '#ff976a';
  }
});

const formattedDueDate = computed(() => {
  if (!props.todo.due_date) return '';
  const date = new Date(props.todo.due_date);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
});

const dueDateTagType = computed(() => {
  if (!props.todo.due_date) return '';

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const dueDate = new Date(props.todo.due_date);
  dueDate.setHours(0, 0, 0, 0);

  const diffDays = Math.floor((dueDate - today) / (1000 * 60 * 60 * 24));

  if (diffDays < 0) return 'danger';
  if (diffDays <= 2) return 'warning';
  return 'primary';
});

// Methods
const onToggleComplete = async () => {
  try {
    const response = await todoApi.updateTodo(props.todo.id, {
      ...props.todo,
      completed: !props.todo.completed
    });
    emit('todo-updated', response);
  } catch (error) {
    showToast('Failed to update todo');
    console.error('Error updating todo:', error);
  }
};

const onDelete = () => {
  showDialog({
    title: 'Delete Todo',
    message: 'Are you sure you want to delete this todo?',
    showCancelButton: true,
  }).then(async () => {
    try {
      await todoApi.deleteTodo(props.todo.id);
      emit('todo-updated', { id: props.todo.id, deleted: true });
      showToast('Todo deleted');
    } catch (error) {
      showToast('Failed to delete todo');
      console.error('Error deleting todo:', error);
    }
  });
};

const onEdit = () => {
  emit('edit-todo', props.todo);
};

const onTodoClick = () => {
  emit('edit-todo', props.todo);
};
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: flex-start;
}

.todo-content {
  display: flex;
  flex-direction: column;
  margin-left: 8px;
}

.todo-title {
  font-weight: 500;
  line-height: 1.4;
}

.todo-description {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.todo-meta {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.completed {
  text-decoration: line-through;
  color: #999;
}
</style>
